<template>
    <Page class="basic company">
        <template #header>
            <EdSelect v-model="params.villageId" :selectParams="taskProjectNameParams" @emit-select-value="projectChange"></EdSelect>
            <EdSelect v-model="params.patrolStatus" :selectParams="patrolStatusParams"></EdSelect>
            <EdSelect v-model="params.patrolType" :selectParams="PatrolTypeParams"></EdSelect>
            <el-date-picker
                v-model="pickerTime"
                type="daterange"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                range-separator="至"
                start-placeholder="开始"
                end-placeholder="结束">
            </el-date-picker>
            <el-input v-model="params.patrolName" placeholder="任务名称"/>
            <el-button class="ed-button ed_black-bottom"  @click="search()"><svg-icon class="svg-middle" icon-class="search-svg"/>查询</el-button>
            <el-button class="ed-button ed_white_bottom" @click="reset()"><svg-icon icon-class="reset-svg"/>重置</el-button>
        </template>
        <PageCard title="巡检任务">
            <template #actions>
                <el-button icon="el-icon-refresh" class="ed-button ed_black_border ed-button36" size="small" @click="reassign" v-has="'patrol:task:assign'">指派</el-button>
                <el-button icon="el-icon-delete" class="ed-button ed_del_top ed-button36" size="small" @click="delSelection" v-has="'patrol:task:delete'">删除</el-button>
                <el-button class="ed-button ed_black-bottom ed-button36" size="small" @click="showPoint" v-has="'patrol:task:add'">新增</el-button>
            </template> 
            <ApiTable :api="tableApi" ref="table" :params="params" @selectionData="selectionData">
                <el-table-column type="selection" width="55" label="序号"  align="center"></el-table-column>
                <el-table-column :show-overflow-tooltip="true" width="125" label="状态" >
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.patrolStatus==0" class="ed-table-bottom ed_2_border">未巡检</el-button>
                        <el-button v-else-if="scope.row.patrolStatus==1" class="ed-table-bottom ed_task_bottom" >巡检中</el-button>
                        <el-button v-else-if="scope.row.patrolStatus==2"  class="ed-table-bottom ed_3_border">已巡检</el-button>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true"  label="进度" width="270">
                    <template slot-scope="scope">
                        <el-progress :percentage="getPercentage(scope.row)" color="#EED096" :format="format(scope.row)"></el-progress>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="patrolNo" label="任务编号"  width="270" >
                    <template slot-scope="scope">
                        <div class="showpointCode" @click="detail(scope.row)">{{scope.row.patrolNo}}</div>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="patrolName" label="任务名称" width="350"></el-table-column>
                <el-table-column :show-overflow-tooltip="true" label="巡检类型" :formatter="setDicType"  width="160">
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="personnelName" label="责任人" width="185"></el-table-column>
                <el-table-column :show-overflow-tooltip="true" prop="endTime" label="任务时间" >
                     <template slot-scope="scope">
                        <span>{{transformDate(scope.row.startTime) + " 至 " + transformDate(scope.row.endTime)}}</span>
                    </template>
                </el-table-column>
            </ApiTable>
        </PageCard>
        <ed-confirm-delete ref="confirmDeleteRef" @confirmDeleteTrue="confirmDeleteTrue()"></ed-confirm-delete>
        <EdDialog :width="'460px'" title="请选择责任人" v-if="showreassign" ref="dialogRef" @close-dialog="closeDialog" @save-dialog="saveDialog">
                    <div class='change_box'>
                        <div class="box_title">{{taskTtile}}转派给</div>
                        <div class="box_list">
                            <div :class="['box_item', (changeRadio==item.id ? 'selected' : '') || item.class]" v-for="item in changeData" :key="item.id">
                                <el-radio v-model="changeRadio" :label="item.id" @change="changeRadioHandle">
                                    <span class="name">{{item.name}}</span>
                                    <div class="job">({{item.orgName}})</div>
                                    <span class="mobile">{{item.mobile}}</span>
                                    <!-- <div class="job">{{item.job}}</div> -->
                                </el-radio>
                            </div>
                        </div>
                    </div>
        </EdDialog>
    </Page>
    
</template>

<script>
import {list,delRow, addPersonnel, getrRepairerData,projectList} from "./api.js";
import Page from '../../components/Page.vue'
import PageCard from 'src/views/components/PageCard.vue'
import ApiTable from 'src/components/ApiTable.vue'
import EdSelect from 'src/components/EdSelect.vue'
import EdDialog from 'src/components/EdDialog.vue'
import { defineComponent } from 'vue'
import EdConfirmDelete from "src/components/EdConfirmDelete.vue";
import {getDictByCode} from "src/api/dictionaries";
export default defineComponent({
    name: 'project',
    components: { Page, PageCard, ApiTable, EdSelect, EdDialog,EdConfirmDelete},
    data() {
        return {
            pickerTime: [],
            params: {
                villageName:'',
                villageId:'',
                patrolStatus: '',
                patrolType:"",
                startTime:'',
                endTime:'',
                patrolName:'',
            },
            taskProjectNameParams:{
                placeholder:"所属项目",
                options: [],
                props: {label:"label", value:"value"}
            },
            patrolStatusParams:{
                placeholder:"请选择巡检状态",
                options: [
                    {value: '0', label:'未巡检'},
                    {value:'1', label:'巡检中'},
                    {value:'2', label:'已巡检'}
                ],
                props: {label:"label", value:"value"}
            },
            PatrolTypeParams:{
                placeholder:"巡检类型",
                options: [],
                props: {label:"label", value:"value"}
            },
            showreassign:false,
            multipleSelection:[],
            ids:[],
            changeRadio: '',
            changeData:[],
            addPersonnel: {
                mobile: "",
                personnelId: 0,
                personnelName: "",
                workId: []
            },
            taskTtile: '',
        }
    },
    activated(){
        this.$nextTick(()=>{
            this.$refs.table.load()
            this.initDic()
        })
        // 获取字典值方式
        getDictByCode("patrolType").then(response => {
            if(response.success) {
                this.PatrolTypeParams.options=response.data.items
            }
        })
    },
    watch:{
        pickerTime: {
            deep: true,
            immediate: true,
            handler(newVal, oldVal) {
                if(newVal && newVal.length > 0) {
                    this.params.startTime = newVal[0]
                    this.params.endTime = newVal[1]
                }
            }
        },
    },
    methods: {
        tableApi:list,
        initDic() {
            // getrRepairerData().then(response => {
            //     console.log(response);
            //     if(response.success) {
            //         this.changeData = response.data
            //     }
            // })
            projectList({page:1,pageSize:999999}).then(response => {
                if(response.success) {
                    let options = response.data.records.map(x => {return {label:x.villageName, value: x.villageId}})
                    this.taskProjectNameParams.options = options
                }
            })
        },
        setDicType(row ,cloumn) {
            let options = this.PatrolTypeParams.options.find(x => x.value == row.patrolType)
            return options.label
        },
        // setDicType(row ,cloumn) {
        // let options = this.PatrolTypeParams.options.find((x) => {
        //     return x.value == row.patrolType
        // })
        // return options.label
        // },
        search(){
            this.$refs.table.load(1)
        },
        reset(){
            this.pickerTime=[]
            this.params= {
                villageName:'',
                villageId:'',
                patrolStatus:"",
                patrolType:"",
                patrolTypeName:'',
                startTime:'',
                endTime:'',
                patrolName:'',
            }
            this.$nextTick(()=>{
                this.$refs.table.load(1,10)
            })
        },
        del(){
            this.$refs.confirmDeleteRef.open("操作确认","是否执行此操作？","warning")
        },
        confirmDeleteTrue(){
            delRow(this.ids).then(response => {
                if(response.success) {
                    this.$message.success({
                        message: '巡检已删除成功！',
                        duration: 2000,
                        center:true
                    });
                    this.$refs.table.load()
                }
            })
        },
        selectionData(value){
            this.multipleSelection = value
        },
        delSelection(){
            if(this.multipleSelection.length>0){
                // 调多选的删除的接口,从数组对象里面取得数组ID
               let ids  = this.multipleSelection.map(x=>{return {id:x.id}})
               this.del()
               this.ids = ids

            }else{
                this.$message.warning({
                    message: '请选择要删除的数据',
                    center:true
                });
            }
        },
        // 指派责任人
        reassign(){
            if(this.multipleSelection.length > 0) {
                let ids = this.multipleSelection.map(item => item.id)
                let personnelNames = this.multipleSelection.map(item => item.personnelName)

                let arr_1 = [], arr_2 = [],userFunction_type='';
                let flag = true
                this.multipleSelection.forEach((v, i)=>{
                // 判断类型
                    if(v['patrolType'] != this.multipleSelection[0]['patrolType']) arr_1.push(v);
                    // 判断小区
                    if(v['villageId'] != this.multipleSelection[0]['villageId']) arr_2.push(v);
                    if(v['patrolStatus']==2) {
                        flag = false
                       return this.$message.error({
                        message:'已巡检状态不能进行指派',
                        center:true,
                       })
                    }
                })
                if(!flag){
                    return
                }
                if(arr_1.length>0) return this.$message.error({message:'所选择巡检类型需一致！',center:true});
                if(arr_2.length>0) return this.$message.error({message:'所选择所属小区需一致！',center:true});
                if(this.multipleSelection[0].patrolType==0)  userFunction_type = '保安'
                if(this.multipleSelection[0].patrolType==1)  userFunction_type = '保洁'
                if(this.multipleSelection[0].patrolType==2)  userFunction_type = '工程'
                if(this.multipleSelection[0].patrolType==3)  userFunction_type = '保洁'
                this.addPersonnel.workId = ids
                if(this.multipleSelection.length == 1) {
                    this.taskTtile = '巡检任务' + this.multipleSelection[0].patrolNo
                } else {
                    this.taskTtile = this.multipleSelection.length + '个巡检任务' + String(personnelNames)
                }
                let params = {
                    villageId: this.multipleSelection[0]['villageId'],
                    // userFunction: this.multipleSelection[0]['patrolType'],
                    userFunction: userFunction_type
                }
                this.showreassign = true
                getrRepairerData(params).then(response => {
                    console.log(response);
                    if(response.success) {
                        this.changeData = response.data
                         this.changeData.forEach(x => {
                            personnelNames.forEach(y => {
                                if(x.name == y) {
                                    x.class='selected'
                                }
                            })
                        })
                    }
                })

            } else {
                this.$message.warning({
                    message: '请选择要指派的数据',
                    center:true
                });
            }
            
        },
        changeRadioHandle(val) {
            this.changeData.forEach((item,index) => {
                if(item.id != val) {
                    item.class = ''
                    this.$set(this.changeData, index,item)
                }
            })
        },
        closeDialog(){
            this.showreassign=false
            this.changeRadio = '';
            this.changeData.forEach((item,index) => {
                item.class = ''
                this.$set(this.changeData, index,item)
            })
        },
        saveDialog(data){
            if(this.changeRadio){
                console.log('aljfjj')
                let person = this.changeData.find(x => x.id == this.changeRadio)
                this.addPersonnel.personnelId = person.id
                this.addPersonnel.personnelName = person.name
                this.addPersonnel.mobile = person.mobile
                    addPersonnel(this.addPersonnel).then(response => {
                        if(response.success) {
                            this.$message.success({
                                message: '转派成功！',
                                duration: 2000,
                                center:true
                            })
                            this.$refs.table.load()
                            this.showreassign=false
                            this.changeRadio = '';
                            this.changeData.forEach((item,index) => {
                                item.class = ''
                                this.$set(this.changeData, index,item)
                            })
                        }
                    }).catch(() => {
                        this.$refs.dialogRef.loading  = false
                    })
            } else {
                this.$message.warning({message:'未勾选，请选择要勾选的责任人',center:true})
                this.$refs.dialogRef.loading  = false
            }
            
            
        },
        showPoint(){
            this.$router.push({
                path: '/patrol/task/add'
            })
        },
        getPercentage(row) {
            if(row.accomplish && row.locationSum) {
                return (row.accomplish / row.locationSum) *100
            } else {
                return 0
            }
        },
        format(percentage) {
            return () => {
                return `${percentage.accomplish +"/" + percentage.locationSum}`
            }
        },
        detail(row){
            this.$router.push({
                path: '/patrol/task/detail',
                query: { id: row.patrolNo }
            })
        },
        projectChange(row) {
            let option = this.taskProjectNameParams.options.find(x=>x.value==row)
            // console.log(option);
            this.params.villageName = option.label
        },
        //标准时间格式转yyyy-MM-dd HH:mm:ss
        transformDate(date) {
            if (date) {
                let dt = new Date(date);
                return dt.getFullYear() + '-' +
                    ((dt.getMonth() + 1) < 10 ? ('0' + (dt.getMonth() + 1)) : (dt.getMonth() + 1)) + '-' +
                    (dt.getDate() < 10 ? ('0' + dt.getDate()) : dt.getDate()) + ' ' +
                    (dt.getHours() < 10 ? ('0' + dt.getHours()) : dt.getHours()) + ':' +
                    (dt.getMinutes() < 10 ? ('0' + dt.getMinutes()) : dt.getMinutes()) 
                    // (dt.getSeconds() < 10 ? ('0' + dt.getSeconds()) : dt.getSeconds())
            } else {
                return ''
            }
        },
    }
})
</script>
<style lang="scss" scoped>
.erweicodeCenter{
    display: flex;
    justify-content: flex-end;
    align-items: center;
}
.el-result .icon-success{
            color:#67C23A
}
:deep .change_box{
        width: 100%;
        border: 1px solid #E4E7ED;
        .box_title{
            width: 100%;
            height: 64px;
            background: #F4F4F4;
            border: 1px solid #E4E7ED;
            padding: 21px 0 21px 12px;
        }
        .box_list{
            height: 360px;
            overflow-y: scroll;
            &::-webkit-scrollbar-thumb{
                background-color: #C1C1C1;
                border-radius: 2px;
            }
            // &::-webkit-scrollbar-track {

            //     background-color: green;
            // }

            // &::-webkit-scrollbar {
            //     width: 20px;
            // }
            .box_item{
                padding: 15px 30px 10px 10px;
                font-family: 'Noto Sans SC';
                font-style: normal;
                font-weight: 400;
                line-height: 22px;
                .name{
                    font-size: 14px;
                    color: #606266;
                }
                .phone{
                    font-size: 14px;
                    color: #909399;
                }
                .job{
                    margin-left: 24px;
                    margin-top: 10px;
                    font-size: 12px;
                    color: #606266;
                }
            }
            .box_item.selected{
                background-color: #FEF9F0;           
            }
            .el-radio__input.is-checked + .el-radio__label{
                // background-color: #FEF9F0;           
            }
            .el-radio__input.is-checked .el-radio__inner{
                border-color: #EED096;
                background-color: #EED096;
            }
        }
    }
    .showpointCode{
        color:#6F8EC6;
        text-decoration:underline ;
        cursor:pointer
    }
    :deep .box_list .box_item .el-radio__label {
        .job {
            margin-bottom: 10px;
        }
        .mobile {
            margin-left: 22px;
        }
    }
</style>